<template>
  <div class="connection-management">
    <div class="page-header">
      <h1>数据库连接管理</h1>
      <el-button type="primary" @click="showCreateDialog">
        <el-icon><Plus /></el-icon>
        新建连接
      </el-button>
    </div>

    <!-- 搜索和筛选 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="连接名称">
          <el-input v-model="searchForm.name" placeholder="请输入连接名称" clearable />
        </el-form-item>
        <el-form-item label="数据库类型">
          <el-select v-model="searchForm.engine" placeholder="请选择数据库类型" clearable>
            <el-option label="MySQL" value="mysql" />
            <el-option label="PostgreSQL" value="postgresql" />
            <el-option label="SQLite3" value="sqlite3" />
            <el-option label="Oracle" value="oracle" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="fetchConnectionList">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 连接列表 -->
    <el-card>
      <el-table :data="connectionList" v-loading="loading" style="width: 100%">
        <el-table-column prop="name" label="连接名称" />
        <el-table-column prop="engine" label="数据库类型" width="120">
          <template #default="scope">
            <el-tag :type="getEngineType(scope.row.engine)">
              {{ getEngineText(scope.row.engine) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="host" label="主机地址" />
        <el-table-column prop="port" label="端口" width="80" />
        <el-table-column prop="database" label="数据库名" />
        <el-table-column prop="username" label="用户名" width="120" />
        <el-table-column prop="is_active" label="状态" width="80">
          <template #default="scope">
            <el-tag :type="scope.row.is_active ? 'success' : 'danger'">
              {{ scope.row.is_active ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="created_at" label="创建时间" width="180" />
        <el-table-column label="操作" width="300">
          <template #default="scope">
            <el-button type="text" size="small" @click="testConnection(scope.row)">
              测试连接
            </el-button>
            <el-button type="text" size="small" @click="viewTables(scope.row)">
              查看表
            </el-button>
            <el-button type="text" size="small" @click="editConnection(scope.row)">
              编辑
            </el-button>
            <el-button type="text" size="small" @click="deleteConnection(scope.row)" style="color: #f56c6c">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="fetchConnectionList"
          @current-change="fetchConnectionList"
        />
      </div>
    </el-card>

    <!-- 创建/编辑连接对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑连接' : '新建连接'"
      width="600px"
    >
      <el-form :model="connectionForm" :rules="connectionRules" ref="connectionFormRef" label-width="100px">
        <el-form-item label="连接名称" prop="name">
          <el-input v-model="connectionForm.name" placeholder="请输入连接名称" />
        </el-form-item>
        <el-form-item label="数据库类型" prop="engine">
          <el-select v-model="connectionForm.engine" placeholder="请选择数据库类型">
            <el-option label="MySQL" value="mysql" />
            <el-option label="PostgreSQL" value="postgresql" />
            <el-option label="SQLite3" value="sqlite3" />
            <el-option label="Oracle" value="oracle" />
          </el-select>
        </el-form-item>
        <el-form-item label="主机地址" prop="host" v-if="connectionForm.engine !== 'sqlite3'">
          <el-input v-model="connectionForm.host" placeholder="请输入主机地址" />
        </el-form-item>
        <el-form-item label="端口" prop="port" v-if="connectionForm.engine !== 'sqlite3'">
          <el-input-number v-model="connectionForm.port" :min="1" :max="65535" />
        </el-form-item>
        <el-form-item label="数据库名" prop="database">
          <el-input v-model="connectionForm.database" placeholder="请输入数据库名" />
        </el-form-item>
        <el-form-item label="用户名" prop="username" v-if="connectionForm.engine !== 'sqlite3'">
          <el-input v-model="connectionForm.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="connectionForm.engine !== 'sqlite3'">
          <el-input v-model="connectionForm.password" type="password" placeholder="请输入密码" show-password />
        </el-form-item>
        <el-form-item label="是否启用">
          <el-switch v-model="connectionForm.is_active" />
        </el-form-item>
        <el-form-item label="设为默认">
          <el-switch v-model="connectionForm.is_default" />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveConnection">保存</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 表列表对话框 -->
    <el-dialog v-model="tablesDialogVisible" title="数据库表列表" width="800px">
      <el-table :data="tableList" v-loading="tablesLoading" style="width: 100%">
        <el-table-column prop="name" label="表名" />
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button type="text" size="small" @click="viewTableStructure(scope.row)">
              查看结构
            </el-button>
            <el-button type="text" size="small" @click="queryTable(scope.row)">
              查询数据
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import api from '@/utils/api'

// 响应式数据
const loading = ref(false)
const dialogVisible = ref(false)
const tablesDialogVisible = ref(false)
const tablesLoading = ref(false)
const isEdit = ref(false)
const connectionFormRef = ref()

const searchForm = reactive({
  name: '',
  engine: ''
})

const connectionForm = reactive({
  id: null,
  name: '',
  host: 'localhost',
  port: 3306,
  database: '',
  username: '',
  password: '',
  engine: 'mysql',
  is_active: true,
  is_default: false
})

const connectionRules = {
  name: [{ required: true, message: '请输入连接名称', trigger: 'blur' }],
  engine: [{ required: true, message: '请选择数据库类型', trigger: 'change' }],
  host: [{ required: true, message: '请输入主机地址', trigger: 'blur' }],
  port: [{ required: true, message: '请输入端口', trigger: 'blur' }],
  database: [{ required: true, message: '请输入数据库名', trigger: 'blur' }],
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
}

const pagination = reactive({
  page: 1,
  pageSize: 20,
  total: 0
})

const connectionList = ref([])
const tableList = ref([])
const currentConnection = ref(null)

// 方法
const fetchConnectionList = async () => {
  loading.value = true
  try {
    const response = await api.get('/database/connections/', {
      params: {
        page: pagination.page,
        page_size: pagination.pageSize,
        ...searchForm
      }
    })
    
    if (response.data.success) {
      let data = response.data.data
      
      if (Array.isArray(data)) {
        connectionList.value = data
        pagination.total = data.length
      } else if (data && Array.isArray(data.results)) {
        connectionList.value = data.results
        pagination.total = data.total || data.results.length
      } else {
        connectionList.value = []
        pagination.total = 0
      }
    }
  } catch (error) {
    console.error('获取连接列表失败:', error)
    ElMessage.error('获取连接列表失败')
  } finally {
    loading.value = false
  }
}

const resetSearch = () => {
  searchForm.name = ''
  searchForm.engine = ''
  pagination.page = 1
  fetchConnectionList()
}

const showCreateDialog = () => {
  isEdit.value = false
  resetConnectionForm()
  dialogVisible.value = true
}

const editConnection = (connection: any) => {
  isEdit.value = true
  Object.assign(connectionForm, connection)
  dialogVisible.value = true
}

const resetConnectionForm = () => {
  Object.assign(connectionForm, {
    id: null,
    name: '',
    host: 'localhost',
    port: 3306,
    database: '',
    username: '',
    password: '',
    engine: 'mysql',
    is_active: true,
    is_default: false
  })
}

const saveConnection = async () => {
  if (!connectionFormRef.value) return
  
  await connectionFormRef.value.validate(async (valid: boolean) => {
    if (!valid) return
    
    try {
      let response
      if (isEdit.value) {
        response = await api.put(`/database/connections/${connectionForm.id}/`, connectionForm)
      } else {
        response = await api.post('/database/connections/', connectionForm)
      }
      
      if (response.data.success) {
        ElMessage.success(isEdit.value ? '连接更新成功' : '连接创建成功')
        dialogVisible.value = false
        fetchConnectionList()
      }
    } catch (error) {
      console.error('保存连接失败:', error)
      ElMessage.error('保存连接失败')
    }
  })
}

const testConnection = async (connection: any) => {
  try {
    const response = await api.post(`/database/connections/${connection.id}/test_connection/`)
    if (response.data.success) {
      ElMessage.success(`连接测试成功，响应时间: ${response.data.response_time?.toFixed(2)}ms`)
    }
  } catch (error) {
    console.error('连接测试失败:', error)
    ElMessage.error('连接测试失败')
  }
}

const viewTables = async (connection: any) => {
  currentConnection.value = connection
  tablesDialogVisible.value = true
  tablesLoading.value = true
  
  try {
    const response = await api.get(`/database/connections/${connection.id}/get_tables/`)
    if (response.data.success) {
      tableList.value = response.data.data.map((name: string) => ({ name }))
    }
  } catch (error) {
    console.error('获取表列表失败:', error)
    ElMessage.error('获取表列表失败')
  } finally {
    tablesLoading.value = false
  }
}

const deleteConnection = async (connection: any) => {
  try {
    await ElMessageBox.confirm('确定要删除这个连接吗？', '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const response = await api.delete(`/database/connections/${connection.id}/`)
    if (response.data.success) {
      ElMessage.success('连接删除成功')
      fetchConnectionList()
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除连接失败:', error)
      ElMessage.error('删除连接失败')
    }
  }
}

const getEngineType = (engine: string) => {
  const types: Record<string, string> = {
    'mysql': 'primary',
    'postgresql': 'success',
    'sqlite3': 'warning',
    'oracle': 'danger'
  }
  return types[engine] || 'info'
}

const getEngineText = (engine: string) => {
  const texts: Record<string, string> = {
    'mysql': 'MySQL',
    'postgresql': 'PostgreSQL',
    'sqlite3': 'SQLite3',
    'oracle': 'Oracle'
  }
  return texts[engine] || engine
}

const viewTableStructure = (table: any) => {
  ElMessage.info('查看表结构功能开发中...')
}

const queryTable = (table: any) => {
  ElMessage.info('查询表数据功能开发中...')
}

// 生命周期
onMounted(() => {
  fetchConnectionList()
})
</script>

<style scoped>
.connection-management {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h1 {
  margin: 0;
  color: #303133;
}

.search-card {
  margin-bottom: 20px;
}

.pagination-wrapper {
  margin-top: 20px;
  text-align: right;
}

.dialog-footer {
  text-align: right;
}
</style>
